package jdbc2;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/*
* 事务
* */
public class JDBCDemo9 {
    public static void main(String[] args) {
        try (Connection conn = DBUtil.getConnection()) {
            //创建连接时是默认提交的,意味着每当执行一条DML语句就COMMIT提交一次
            //如果需要自己控制事务,需要关闭自动提交
            conn.setAutoCommit(false);

            Statement stmt = conn.createStatement();
            String sql = "INSERT INTO userinfo(username,password,nickname,age) " +
                    "VALUES('SuperMan','123456','超人强','8')";
            stmt.executeUpdate(sql);

            System.out.println("插入完毕");

            ResultSet rs = stmt.executeQuery("SELECT username FROM userinfo");
            while (rs.next()){
                System.out.println(rs.getString("username"));
            }
            conn.commit();
            //conn.rollback();
            //之后会开启新的事务
            //开始新的增删改查
            //要么COMMIT提交,要么ROLLBACK回滚

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
